/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.buanalintas.sandals.pos.item;

import com.buanalintas.bynga.Action;
import com.buanalintas.bynga.Component;
import com.buanalintas.bynga.Converter;
import com.buanalintas.bynga.Dictionary;
import com.buanalintas.bynga.Field;
import com.buanalintas.bynga.Page;
import com.buanalintas.bynga.Template;
import com.buanalintas.bynga.Utility;
import com.buanalintas.sandals.pos.entities.PosMasterItem;
import com.buanalintas.sandals.pos.entities.PosMasterSize;
import java.util.List;
import javax.servlet.http.HttpSession;

/**
 *
 * @author user
 */
public class AddItem {

    public static StringBuffer process(Page page) {
        page.beforeAdd();
        StringBuffer content = Utility.load("/com/buanalintas/bynga/resources/themes/bep/content.html");
        Template template = new Template("add.html");
        String result = doAction(page);
        if (Utility.getPostParameter(page, "msg") != null) {
            result = Utility.decode(Utility.getPostParameter(page, "msg"));
        }
        if (result == null) {
            template.addElement(Template.INFORMATION, null);
        } else {
            StringBuffer information = template.getEmptyElement(Template.INFORMATION);
            if (result.startsWith("err:")) {
                Utility.replaceAll(information, Template.INFORMATION_CLASS, "err");
                Utility.replaceAll(information, Template.INFORMATION_MESSAGE, result.substring(4));
            } else {
                Utility.replaceAll(information, Template.INFORMATION_CLASS, "ok");
                Utility.replaceAll(information, Template.INFORMATION_MESSAGE, result.substring(3) + "<script>opener.location.href = '?m=" + page.getMenu().getMenuName()+ "&a=" + Action.TRANS_DETAIL_LIST.getName() + "';</script>");
            }
            template.addElement(Template.INFORMATION, information);
        }

        template.addValue(Template.ADD_JAVASCRIPT, "<script type=\"text/javascript\" src=\"?file=validation.js\"></script>" + page.addJavascript());

        template.addValue(Template.ADD_FORM_NAME, "form-" + page.getMenu().getMenuId());
        template.addValue(Template.ADD_FORM_ACTION, "?m=" + page.getMenu().getMenuName() + "&a=" + page.getAction().getName());

        template.addValue(Template.ADD_CAPTION_VARIABLE, Dictionary.getValue(page, "Variable"));
        template.addValue(Template.ADD_CAPTION_VALUE, Dictionary.getValue(page, "Value"));

        StringBuffer jsValidation = new StringBuffer();
        StringBuffer jsBottom = new StringBuffer();
        jsValidation.append("var form = document.getElementById('form-").append(page.getMenu().getMenuId()).append("');");
        int number = 0;
        page.fillGroups();
        template.addValue(Template.ADD_FORM_PROPERTIES, page.isAddMultiPart() ? "enctype=\"multipart/form-data\"" : "");
        for (Page.Group g : page.getGroupsAdd()) {
            StringBuffer group = template.getEmptyElement(Template.ADD_INFO);
            Utility.replaceAll(group, Template.ADD_INFORMATION, g.getInfo());
            template.addRepeat(Template.ADD, group);
            for (Field f : g.getFields()) {
                if (jsBottom.toString().equals("")) {
                    boolean first = false;
                    if (!first && f.getInputProperties() == null) {
                        first = true;
                    }
                    if (!first && f.getInputProperties().toLowerCase().indexOf("readonly") == -1) {
                        first = true;
                    }
                    if (first) {
                        jsBottom.append("<script type=\"text/javascript\">document.getElementById('form-").append(page.getMenu().getMenuId()).append("').").append(f.getName()).append(".focus();</script>");
                    }
                }
                if (f.isDoubleEntry()) {
                    StringBuffer row = template.getEmptyElement(Template.ADD);
                    Utility.replaceAll(row, Template.ADD_CLASS, number % 2 == 0 ? "1" : "2");
                    if (f.isRequired()) {
                        Utility.replaceAll(row, Template.ADD_VARIABLE, "<strong>" + Utility.upperCaseFirstWords(Dictionary.getValue(page, f.getCaption())) + "</strong>" + (f.getInfo() == null ? "" : "<br><div class=\"variable-info\">" + Dictionary.getValue(page, f.getInfo()) + "</div>"));
                    } else {
                        Utility.replaceAll(row, Template.ADD_VARIABLE, Utility.upperCaseFirstWords(Dictionary.getValue(page, f.getCaption())) + (f.getInfo() == null ? "" : "<br><div class=\"variable-info\">" + Dictionary.getValue(page, f.getInfo()) + "</div>"));
                    }
                    Utility.replaceAll(row, Template.ADD_VALUE, Component.createAddComponent(page, f, "x").toString());
                    template.addRepeat(Template.ADD, row);
                    number++;
                    row = template.getEmptyElement(Template.ADD);
                    Utility.replaceAll(row, Template.ADD_CLASS, number % 2 == 0 ? "1" : "2");
                    if (f.isRequired()) {
                        Utility.replaceAll(row, Template.ADD_VARIABLE, "<strong>" + Dictionary.getValue(page, "Retype") + " " + Utility.upperCaseFirstWords(Dictionary.getValue(page, f.getCaption())) + "</strong>" + (f.getInfo() == null ? "" : "<br><div class=\"variable-info\">" + Dictionary.getValue(page, f.getInfo()) + "</div>"));
                    } else {
                        Utility.replaceAll(row, Template.ADD_VARIABLE, Utility.upperCaseFirstWords(Dictionary.getValue(page, f.getCaption())) + (f.getInfo() == null ? "" : "<br><div class=\"variable-info\">" + Dictionary.getValue(page, f.getInfo()) + "</div>"));
                    }
                    Utility.replaceAll(row, Template.ADD_VALUE, Component.createAddComponent(page, f, "y").toString());
                    template.addRepeat(Template.ADD, row);
                    number++;
                } else {
                    StringBuffer row = template.getEmptyElement(Template.ADD);
                    Utility.replaceAll(row, Template.ADD_CLASS, number % 2 == 0 ? "1" : "2");
                    //Utility.replaceAll(row, Template.ADD_VARIABLE, Dictionary.getValue(page, f.getCaption()) + (f.isRequired() ? "*" : ""));
                    if (f.isRequired()) {
                        Utility.replaceAll(row, Template.ADD_VARIABLE, "<strong>" + Utility.upperCaseFirstWords(Dictionary.getValue(page, f.getCaption())) + "</strong>");
                    } else {
                        Utility.replaceAll(row, Template.ADD_VARIABLE, Utility.upperCaseFirstWords(Dictionary.getValue(page, f.getCaption())));
                    }
                    Utility.replaceAll(row, Template.ADD_VALUE, Component.createAddComponent(page, f).toString());
                    template.addRepeat(Template.ADD, row);
                    number++;
                }
            }
        }
        page.createValidator(jsValidation, page.getGroupsAdd());
        jsValidation.append("if (!confirm('").append(Dictionary.getValue(page, "Continue saving data?")).append("')) { return false; }");
        template.addValue(Template.ADD_JAVASCRIPT_CONTENT, jsValidation.toString());
        template.addValue(Template.ADD_JAVASCRIPT_BOTTOM, jsBottom.toString() + "<script type=\"text/javascript\">" + page.getJavaScript() + "</script>");
        template.addValue(Template.ADD_DETAIL, "");
        template.addElement(Template.ADD_INFO, null);
        template.addValue(Template.FORM_REMARKS, Template.getFormRemarks(page).toString());

        Utility.replaceAll(content, Template.CONTENT_CONTENT, template.process().toString());
        Utility.replaceAll(content, Utility.getElement(content, Template.CONTENT_TITLE).toString(), "");
        return content;
    }

    private static String doAction(Page page) {
        HttpSession session = page.getRequest().getSession();
        if (page.isSubmited()) {
            String valid = validation(page);
            if (valid == null) {
                try {
                    Object data = getData(page);
                    valid = page.validate(data);
                    if (valid == null) {
                        try {
                            page.getController().beforeInsert(data);
                            //((List) session.getAttribute("transactions")).add(data);

                            PosMasterItem item = (PosMasterItem) data;
                            String[] sizes = item.getItemSize().split(",");
                            List list = (List) page.getRequest().getSession().getAttribute("transactions");
                            for (String s : sizes) {
                                PosMasterSize size = (PosMasterSize) page. getController().getData(PosMasterSize.class, s);
                                PosMasterItem d = new PosMasterItem();
                                Utility.update(d, item);
                                d.setItemSizeId(size);
//                                d.setPurchaseOrderDetailItemId(item.getPurchaseOrderDetailItemId());
                                list.add(d);
                            }
                            page.getRequest().getRequestDispatcher("?m=" + page.getMenu().getMenuName() + "&a=" + page.getAction().getName() + "&msg=" + Utility.encode("ok:" + Dictionary.getValue(page, "Data") + " " + page.getObjectInfo(data) + " " + Dictionary.getValue(page, "inserted succesfully"))).forward(page.getRequest(), page.getResponse());
                            return "ok:" + Dictionary.getValue(page, "Data") + " " + page.getObjectInfo(data) + " " + Dictionary.getValue(page, "inserted succesfully");
                        } catch (Exception e) {
                            return "err:" + Dictionary.getValue(page, "Data") + " " + page.getObjectInfo(data) + " " + Dictionary.getValue(page, "inserted failed") + ":" + e.getMessage();
                        }
                    } else {
                        return "err:" + valid;
                    }
                } catch (Exception e) {
                    page.catchException(e);
                    //Logger.log(e);
                    return "err:" + Dictionary.getValue(page, "Insert failed, error") + ": " + e.getMessage();
                }
            }
            return "err:" + valid;
        }
        return page.doAction();
    }

    private static Object getData(Page page) throws InstantiationException, IllegalAccessException {
        Object data = page.getTheClass().newInstance();
        page.fillGroups();
        for (Field f : page.getFieldsAdd()) {
            try {
                Converter.fillObject(data, page, f);
            } catch (Exception e) {
                //Logger.log(e);
            }
        }
        return data;
    }

    private static String validation(Page page) {
        for (Field f : page.getFieldsAdd()) {
            if (f.isRequired()) {
                if (f.isDoubleEntry()) {
                    String valueX = Utility.getFormValue(page, f, "x");
                    String valueY = Utility.getFormValue(page, f, "y");
                    if (valueX == null) {
                        return Dictionary.getValue(page, f.getCaption()) + " " + Dictionary.getValue(page, "required");
                    } else if (valueX.trim().equals("")) {
                        return Dictionary.getValue(page, f.getCaption()) + " " + Dictionary.getValue(page, "required");
                    }
                    if (valueY == null) {
                        return Dictionary.getValue(page, "Retype") + " " + Dictionary.getValue(page, f.getCaption()) + " " + Dictionary.getValue(page, "required");
                    } else if (valueY.trim().equals("")) {
                        return Dictionary.getValue(page, "Retype") + " " + Dictionary.getValue(page, f.getCaption()) + " " + Dictionary.getValue(page, "required");
                    }
                } else {
                    String value = Utility.getFormValue(page, f);
                    if (value == null) {
                        return Dictionary.getValue(page, f.getCaption()) + " " + Dictionary.getValue(page, "required");
                    } else if (value.trim().equals("")) {
                        return Dictionary.getValue(page, f.getCaption()) + " " + Dictionary.getValue(page, "required");
                    }
                }
            }
            if (f.isDoubleEntry()) {
                String valueX = Utility.getFormValue(page, f, "x");
                String valueY = Utility.getFormValue(page, f, "y");
                if (f.isValidate() || (valueX != null && !valueX.trim().equals(""))) {
                    try {
                        Converter.convert(valueX, f);
                    } catch (Exception e) {
                        return Dictionary.getValue(page, f.getCaption()) + " \"" + valueX + "\" " + Dictionary.getValue(page, "not accepted, required") + " " + f.getFieldType().getSimpleName();
                    }
                }
                if (!valueX.equals(valueY)) {
                    return Dictionary.getValue(page, f.getCaption()) + " " + Dictionary.getValue(page, "and retype") + " " + Dictionary.getValue(page, f.getCaption()) + " " + Dictionary.getValue(page, "does not match") + "";
                }
            } else {
                String value = Utility.getFormValue(page, f);
                if (f.isValidate() || (value != null && !value.trim().equals(""))) {
                    try {
                        Converter.convert(value, f);
                    } catch (Exception e) {
                        return Dictionary.getValue(page, f.getCaption()) + " \"" + value + "\" " + Dictionary.getValue(page, "not accepted, required") + " " + f.getFieldType().getSimpleName();
                    }
                }
            }

        }
        return null;
    }
}
